#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Float, Integer, Boolean, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

from controls import data_sight_base_mysql
from controls import data_sight_desc_mysql
from controls import data_sight_img_mysql

metadata = MetaData()
Session = sessionmaker()  # 使用sessionmaker()不需要显示调用session.close()
Session.configure(bind=engine)

"""city_base collection has
    cityid:            城市id(int）
    provid:            省会id(int）
    name:            城市名字拼音(string）
    cname:             城市名汉字(string）
    pos_x:            地图横坐标(float）
    pos_y:             地图纵坐标(float）
    bgcolortop:        地图顶部北京颜色(string)
    bgcolorend:        地图底部北京颜色(string)
    version:           地图版本号(int）
    versioninfo:       景点信息版本号(int）
"""


class CityBaseItem(object):
    """docstring for CityBaseItem"""

    def to_dict(self):
        res = {}
        res['cityid'] = self.cityid
        res['provid'] = self.provid
        res['name'] = self.name
        res['cname'] = self.cname
        res['pos_x'] = float(self.pos_x)
        res['pos_y'] = float(self.pos_y)
        res['bgcolortop'] = self.bgcolortop
        res['bgcolorend'] = self.bgcolorend
        res['version'] = self.version
        res['versioninfo'] = self.versioninfo
        return res

    def __repr__(self):
        print "%d" % (self.cityid)


city_base_table = Table(
    'city_base', metadata,
    Column('id', Integer, primary_key=True),
    Column('cityid', Integer, index=True, unique=True, nullable=False),
    Column('provid', Integer, index=True, nullable=False),
    Column('name', Unicode(65), nullable=False),
    Column('cname', Unicode(65), nullable=False),
    Column('pos_x', Float(6, 2), nullable=False),
    Column('pos_y', Float(6, 2), nullable=False),
    Column('bgcolortop', String(8), default='000000ff', nullable=False),
    Column('bgcolorend', String(8), default='000000ff', nullable=False),
    Column('version', Integer, default=0),
    Column('versioninfo', Integer, default=0)
)

mapper(CityBaseItem, city_base_table)


def create_city_base_table_if_not_exist():
    metadata.create_all(engine)


def add_city_base_item(p_item):
    item = CityBaseItem()
    item.cityid = p_item['cityid']
    item.provid = p_item['provid']
    item.name = p_item['name']
    item.cname = p_item['cname']
    item.pos_x = p_item['pos_x']
    item.pos_y = p_item['pos_y']
    item.bgcolortop = p_item['bgcolortop']
    item.bgcolorend = p_item['bgcolorend']
    item.version = p_item['version']
    item.versioninfo = p_item['version']  # 合并只使用version字段
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        data_sight_base_mysql.create_sight_base_item_table_if_not_exist(item.cityid)
        data_sight_desc_mysql.create_sight_desc_item_table_if_not_exist(item.cityid)
        data_sight_img_mysql.create_sight_img_item_table_if_not_exist(item.cityid)
        # data_journey_base_mysql.create_journey_base_item_table_if_not_exist(item.cityid)
        # data_journey_info_mysql.create_journey_info_item_table_if_not_exist(item.cityid)
        # data_journey_image_mysql.create_journey_image_item_table_if_not_exist(item.cityid)
        # data_journey_mark_mysql.create_journey_mark_item_table_if_not_exist(item.cityid)
        return True

    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def update_city_base_item(p_item):
    if not p_item:
        return False
    try:
        updateField = {
            CityBaseItem.provid: p_item['provid'],
            CityBaseItem.name: p_item['name'],
            CityBaseItem.cname: p_item['cname'],
            CityBaseItem.pos_x: p_item['pos_x'],
            CityBaseItem.pos_y: p_item['pos_y'],
            CityBaseItem.bgcolortop: p_item['bgcolortop'],
            CityBaseItem.bgcolorend: p_item['bgcolorend'],
            CityBaseItem.version: p_item['version'],
            CityBaseItem.versioninfo: p_item['version']  # 合并只使用version字段
        }

        session = Session()
        session.query(CityBaseItem).filter(CityBaseItem.cityid == p_item['cityid']).update(updateField,
                                                                                           synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def delete_city_base_item(p_cityid):
    try:
        session = Session()
        session.query(CityBaseItem).filter(CityBaseItem.cityid == p_cityid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


'''
get all published cities. 
unpublished cities wont be return(version or versioninfo is 0, mean this city is unpublished)
'''


def get_city_all():
    try:
        session = Session()
        items = session.query(CityBaseItem).filter(CityBaseItem.versioninfo != 0, CityBaseItem.version != 0).all()
        res = []
        for item in items:
            res.append(item.to_dict())
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
get all cities. 
后台运维使用，城市更新信息用
'''


def get_city_all_by_bg():
    try:
        session = Session()
        items = session.query(CityBaseItem).filter().order_by(CityBaseItem.cityid.asc()).all()
        res = []
        for item in items:
            res.append(item.to_dict())
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_city_base_by_id(cityid):
    try:
        session = Session()
        item = session.query(CityBaseItem).filter(CityBaseItem.cityid == cityid).first()
        return item.to_dict()
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
p_cityid
p_version
p_versioninfo
'''


def update_city_version_by_cityid(p_cityid, p_version=0, p_versioninfo=0):
    if p_version == 0 and p_versioninfo == 0:
        return False
    try:
        updateField = {}
        if p_version != 0:
            updateField[CityBaseItem.version] = p_version
            updateField[CityBaseItem.versioninfo] = p_version  # 合并只使用version字段
        if p_versioninfo != 0:
            updateField[CityBaseItem.versioninfo] = p_versioninfo
        session = Session()
        session.query(CityBaseItem).filter(CityBaseItem.cityid == p_cityid).update(updateField,
                                                                                   synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


if __name__ == "__main__":
    create_city_base_table_if_not_exist()
    '''
    test_item = {'cityid': 1,
                 'provid': 1,
                 'name': 'beijing',
                 'cname': '北京',
                 'pos_x': 100.01,
                 'pos_y': 100.01,
                 'versioninfo': 1,
                 'version': 1}
    add_city_base_item(test_item)
    res = get_city_all()
    print  res
    a = len( res )
    print a
    '''
    print get_city_all()
